//
//  NetworkManager.swift
//  SinaWeiBo
//
//  Created by Leon 笑 竹 on 2017/8/4.
//  Copyright © 2017年 Leon 笑 竹. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethods{
    
    case GET
    case POST
}


class NetworkManager: AFHTTPSessionManager {
    
    static let shared = NetworkManager()
    var access_Token : String? = "2.00Hx2rnGsdYkFBc9da7cd0a99fxiYB"//: String? //
    
    /// Token请求封装
    ///
    /// - Parameters:
    ///   - methods: 请求方法
    ///   - url: 地址
    ///   - params: 参数
    ///   - completion: 回调
    func tokenRequest(methods:HTTPMethods = .GET, url : String, params : [String : AnyObject]?, completion : @escaping (AnyObject?,Bool) -> ()){
        
        //没有token的情况下
        guard let token = access_Token else {
            
            //FIXME: - 发送错误通知，提示用户登录
            print("没有token! 需要登录")
            
            completion(nil, false)
            return
        }
        
        //创建字典
        var params = params
        if params == nil {
            params = [String : AnyObject]()
        }
        
        params!["access_token"] = token  as AnyObject
        //调用请求
        request(url: url, params: params, completion: completion)
    }
    
    
    /// 网络请求封装
    ///
    /// - Parameters:
    ///   - methods: GET或者POST
    ///   - url: 地址
    ///   - params: 拼装参数
    ///   - completion: 完成回调
    func request(methods:HTTPMethods = .GET, url : String, params : [String : AnyObject]?, completion : @escaping (AnyObject?,Bool) -> ()){
        
        //闭包回调（成功）
        let success = {(task : URLSessionDataTask, json : Any?) -> () in
            
            completion(json as AnyObject, true)
        }
        
        //闭包回调 (失败)
        let failure = {(task : URLSessionDataTask?, error : Error) -> () in
            
            //处理错误码
            if(task?.response as? HTTPURLResponse)?.statusCode == 403{
                
                print("Token过期了");
                
                //FIXME: - 发送错误通知，谁接收到谁处理，提示用户再次登录
                
            }
            
            print("网络请求失败 \(error)")
            
            completion(nil, false)
        }
        
        
        if methods == .GET {
            
            get(url, parameters: params, progress: nil, success: success, failure: failure)
            
        }else{
            
            post(url, parameters: params, progress: nil, success: success, failure: failure)
            
        }
    }
    
    
    /// //上传图像方法
    ///
    /// - Parameters:
    ///   - url: 上传地址
    ///   - params: 上传参数
    ///   - image: 图像文件
    ///   - completion: 完成回调
    func uploadImage(url : String, params : [String : AnyObject], image : UIImage,completion : @escaping (Any?,Bool) -> ()){
        
        //闭包回调（成功）
        let success = {(task : URLSessionDataTask, json : Any?) -> () in
            
            completion(json, true)
        }
        
        //闭包回调 (失败)
        let failure = {(task : URLSessionDataTask?, error : Error) -> () in
            
            print("网络请求失败 \(error)")
            
            completion(nil, false)
        }
        
        post(url, parameters: params, constructingBodyWith: { (AFMultipartFormData) in
            
            //将图片转换为data格式
            let imageData = UIImageJPEGRepresentation(image, 0.9)
            
            //用时间拼接fileName
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyyMMddHHmmss";
            let str = formatter.string(from: Date())
            let fileName = "\(str)" + ".jpg"
            AFMultipartFormData.appendPart(withFileData: imageData!, name: "file", fileName: fileName, mimeType: "image/jepg")
            
        }, progress: { (Progress) in
            
            print("---\(Progress.completedUnitCount / Progress.totalUnitCount)")
            
        }, success: success, failure: failure)
    }
    
}
